package com.lemon.smartsafetynew.ui.activity.user;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.google.gson.Gson;
import com.lemon.android.http.AesEncryptor;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.ApplicationInfo;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafetynew.ui.activity.base.BaseActivity;
import com.lemon.smartsafety.utils.app.UIHelper;
import com.lemon.smartsafetynew.entity.User;
import com.lemon.smartsafetynew.entity.common.CommonBo;
import com.lemon.smartsafetynew.entity.user.LoginNameVo;
import com.lemon.smartsafetynew.net.services.AccountServices;
import com.lemon.smartsafetynew.ui.activity.MainNewActivity;
import com.lemon.smartsafetynew.ui.adapter.user.LoginNameAdapter;
import com.lemon.smartsafetynew.util.common.AppSharePreferenceUtil;
import com.lemon.smartsafetynew.util.constants.KeyConstants;
import com.lemon.smartsafetynew.util.constants.SafeCloudConstants;
import com.lemon.smartsafetynew.util.user.AccountUtil;
import com.lemon.smartsafetynew.util.user.UserTypeUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * 登陆页面
 * Created by Andrew on 2017/7/17.
 */

public class UserLoginActivity extends BaseActivity
        implements View.OnLayoutChangeListener, LoginNameAdapter.DeleteListener {

    @Bind(R.id.account_edit)
    EditText accountEdit;

    @Bind(R.id.iv_popwindow)
    ImageView ivPopwindow;

    @Bind(R.id.password_edit)
    EditText passwordEdit;

    @Bind(R.id.login_btn)
    Button loginBtn;

    @Bind(R.id.remember_account_cb)
    CheckBox rememberAccountCb;

    @Bind(R.id.txtCleanLoginName)
    TextView txtCleanLoginName;

    @Bind(R.id.txtCleanPwd)
    TextView txtCleanPwd;

    private View activityRootView;
    private String account;
    private String password;
    private List<LoginNameVo> loginNameVoList;
    private int keyHeight = 0;
    private PopupWindow popupWindow;
    private LoginNameAdapter loginNameAdapter;

    private boolean isKeyBoardOn = false;
    private static final int MAX_SAVE_ACCOUNT_NUM = 5; //最多保留5个账号

    private boolean isLoginNameFocus = false;
    private boolean isPasswordFocus = false;

    //输入法管理器
    private InputMethodManager mInputMethodManager;

    @Override
    protected void getBundleArgs() {

    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_user_login;
    }

    @Override
    protected void initViews() {

        mInputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

        activityRootView = findViewById(R.id.root_layout);
        //阀值设置为屏幕高度的1/3
        keyHeight = this.getWindowManager().getDefaultDisplay().getHeight() / 3;

        // ===== 用户账号下拉列表 =====
        loginNameVoList = AccountUtil.getLoginListName();
        if (null == loginNameVoList) {
            loginNameVoList = new ArrayList<>();
            ivPopwindow.setVisibility(View.GONE);
        } else {
            if (loginNameVoList.size() > 0) {
                ivPopwindow.setVisibility(View.VISIBLE);
                accountEdit.setText(loginNameVoList.get(0).getLoginName());
                passwordEdit.setText(AesEncryptor.decrypt(loginNameVoList.get(0).getLoginPassword()));
                loginBtn.setEnabled(true);
            } else {
                ivPopwindow.setVisibility(View.GONE);
            }
        }
        ivPopwindow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                accountEdit.setFocusable(false);
                passwordEdit.setFocusable(false);

                if (isKeyBoardOn) {
                    try {
                        if (mInputMethodManager != null && mInputMethodManager.isActive()) {
                            mInputMethodManager.hideSoftInputFromWindow(accountEdit.getWindowToken(), 0);// 隐藏输入法
                            mInputMethodManager.hideSoftInputFromWindow(passwordEdit.getWindowToken(), 0);// 隐藏输入法
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return;
                }

                showPopupwindow();
            }
        });

        // =========== accountEdit ===========
        accountEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (isLoginNameFocus) {
                    if (!"".equals(s.toString())) {
                        if (txtCleanLoginName != null)
                            txtCleanLoginName.setVisibility(View.VISIBLE);
                    } else {
                        if (txtCleanLoginName != null)
                            txtCleanLoginName.setVisibility(View.GONE);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                passwordEdit.setText("");
                password = passwordEdit.getText().toString().trim();
                account = accountEdit.getText().toString().trim();
                if (checkAccountName(account) && checkPassword(password)) {
                    loginBtn.setEnabled(true);
                } else {
                    loginBtn.setEnabled(false);
                }
            }
        });

        accountEdit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    isLoginNameFocus = true;
                    // 此处为得到焦点时的处理内容
                    if (!"".equals(accountEdit.getText().toString().trim())) {
                        if (txtCleanLoginName != null)
                            txtCleanLoginName.setVisibility(View.VISIBLE);
                    } else {
                        if (txtCleanLoginName != null)
                            txtCleanLoginName.setVisibility(View.GONE);
                    }
                } else {
                    isLoginNameFocus = false;
                    if (txtCleanLoginName != null)
                        txtCleanLoginName.setVisibility(View.GONE);
                }
            }
        });

        // =========== passwordEdit ===========
        passwordEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (isPasswordFocus) {
                    if (!"".equals(s.toString())) {
                        if (txtCleanPwd != null)
                            txtCleanPwd.setVisibility(View.VISIBLE);
                    } else {
                        if (txtCleanPwd != null)
                            txtCleanPwd.setVisibility(View.GONE);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                password = passwordEdit.getText().toString().trim();
                account = accountEdit.getText().toString().trim();
                if (checkAccountName(account) && checkPassword(password)) {
                    loginBtn.setEnabled(true);
                } else {
                    loginBtn.setEnabled(false);
                }
            }
        });

        passwordEdit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    isPasswordFocus = true;
                    // 此处为得到焦点时的处理内容
                    if (!"".equals(passwordEdit.getText().toString().trim())) {
                        if (txtCleanPwd != null)
                            txtCleanPwd.setVisibility(View.VISIBLE);
                    } else {
                        if (txtCleanPwd != null)
                            txtCleanPwd.setVisibility(View.GONE);
                    }
                } else {
                    isPasswordFocus = false;
                    if (txtCleanPwd != null)
                        txtCleanPwd.setVisibility(View.GONE);
                }
            }
        });

    }

    private void showPopupwindow() {

        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(this).inflate(
                R.layout.pop_list, null);

        popupWindow = new PopupWindow(contentView,
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setTouchable(true);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        final ListView myListView = (ListView) contentView.findViewById(R.id.listView);
        loginNameAdapter = new LoginNameAdapter(this, loginNameVoList, this);
        myListView.setAdapter(loginNameAdapter);
        myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                accountEdit.setText(loginNameVoList.get(position).getLoginName());
                passwordEdit.setText(AesEncryptor.decrypt(loginNameVoList.get(position).getLoginPassword()));
                popupWindow.dismiss();
            }
        });


        // 设置好参数之后再show
        popupWindow.showAsDropDown(ivPopwindow);

    }

    @Override
    protected void onResume() {
        super.onResume();
        activityRootView.addOnLayoutChangeListener(this);
    }

    @Override
    protected void onPause() {
        super.onPause();

        try {
            if (mInputMethodManager != null && mInputMethodManager.isActive()) {
                mInputMethodManager.hideSoftInputFromWindow(accountEdit.getWindowToken(), 0);// 隐藏输入法
                mInputMethodManager.hideSoftInputFromWindow(passwordEdit.getWindowToken(), 0);// 隐藏输入法
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnClick({R.id.forget_password_tv, R.id.login_btn, R.id.register_btn, R.id.txtCleanLoginName, R.id.txtCleanPwd, R.id.password_edit, R.id.account_edit})
    public void onViewClicked(View view) {
        Intent mIntent;
        switch (view.getId()) {
            case R.id.forget_password_tv:
                mIntent = new Intent(UserLoginActivity.this, UserForgetPasswordActivity.class);
                startActivity(mIntent);
                break;
            case R.id.login_btn:
                password = passwordEdit.getText().toString().trim();
                account = accountEdit.getText().toString().trim();
                if (checkAccountName(account)) {
                    if (checkPassword(password) && matcherPassword(password)) {
                        AccountServices.init().doLogin(account, AesEncryptor.encrypt(password), "");
                    } else {
                        mHUDUtil.showErrorTip(getString(R.string.password_error));
                    }
                } else {
                    mHUDUtil.showErrorTip(getString(R.string.account_name_error));
                }

                break;
            case R.id.register_btn:
                mIntent = new Intent(UserLoginActivity.this, UserRegisterActivity.class);
                startActivity(mIntent);
                break;
            case R.id.txtCleanLoginName:
                accountEdit.setText("");
                break;
            case R.id.txtCleanPwd:
                passwordEdit.setText("");
                break;
            case R.id.password_edit:
                passwordEdit.setFocusable(true);//设置输入框可聚集
                passwordEdit.setFocusableInTouchMode(true);//设置触摸聚焦
                passwordEdit.requestFocus();//请求焦点
                passwordEdit.findFocus();//获取焦点
                mInputMethodManager.showSoftInput(passwordEdit, InputMethodManager.SHOW_FORCED);// 显示输入法
                break;
            case R.id.account_edit:
                accountEdit.setFocusable(true);//设置输入框可聚集
                accountEdit.setFocusableInTouchMode(true);//设置触摸聚焦
                accountEdit.requestFocus();//请求焦点
                accountEdit.findFocus();//获取焦点
                mInputMethodManager.showSoftInput(accountEdit, InputMethodManager.SHOW_FORCED);// 显示输入法
                break;
        }
    }

    @Override
    public void delete(int position) {

        if (accountEdit.getText().toString().trim().equals(loginNameVoList.get(position).getLoginName())) {
            accountEdit.setText("");
            passwordEdit.setText("");
        }

        loginNameVoList.remove(position);
        AccountUtil.setLoginNameList(loginNameVoList);

        loginNameAdapter.notifyDataSetChanged();
        if (loginNameVoList.size() == 0) {
            ivPopwindow.setVisibility(View.GONE);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMainThread(HttpCallbackEvent<List<User>> event) {
        if (KeyConstants.URL_ACCOUNT_LOGIN.equals(event.getTag())) {
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                showDialog();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                cancelDialog();
                if (event.getEventResult() == Constants.Result.SUCCESS) {

                    List<User> users = event.getObj();

                    // ====== 用户记录保存 begin ======
                    if (rememberAccountCb.isChecked()) {

                        LoginNameVo loginNameVo = new LoginNameVo();
                        loginNameVo.setLoginName(account);
                        loginNameVo.setLoginPassword(AesEncryptor.encrypt(password));

                        if (loginNameVoList.size() == 0) {
                            loginNameVoList.add(loginNameVo);
                        } else {

                            Iterator<LoginNameVo> iterator = loginNameVoList.iterator();
                            while (iterator.hasNext()) {
                                LoginNameVo vo = iterator.next();
                                if (account.equals(vo.getLoginName())) {
                                    iterator.remove();
                                }
                            }

                            if (loginNameVoList.size() >= MAX_SAVE_ACCOUNT_NUM) {
                                int size = loginNameVoList.size();
                                for (int i = 1; i <= loginNameVoList.size() - 4; i++) {
                                    loginNameVoList.remove(size - i);
                                }
                                loginNameVoList.add(0, loginNameVo);
                            } else {
                                loginNameVoList.add(0, loginNameVo);
                            }

                        }
                        AccountUtil.setLoginNameList(loginNameVoList);
                    }
                    // ====== 用户记录保存 end ======

                    // ====== 用户身份判断 begin ======
                    if (users != null && !users.isEmpty()) {
                        /**
                         * code为2时，为多身份的情况
                         */

                        if (event.getCode() == CommonBo.Account.LOGIN_ERROR_MOREUSER.getValue()) {
                            Bundle bundle = new Bundle();
                            bundle.putString(KeyConstants.KEY_USER_LIST, new Gson().toJson(users));
                            bundle.putString(KeyConstants.KEY_USER_ACCOUNT, accountEdit.getText().toString().trim());
                            bundle.putString(KeyConstants.KEY_USER_PD, AesEncryptor.encrypt(passwordEdit.getText().toString().trim()));
                            UIHelper.showActivity(UserLoginActivity.this, bundle, UserAccountChooseActivity.class);

                        } else {

                            //  企事业人员/政府机关单位可以登陆条件：
                            //  条件一：企事业单位登陆人的companyId不为能为空
                            //  条件二：用户类型是产品支持
                            //  条件三：用户类型是政府人员
                            User user = users.get(0);
                            if (user.getCompanyId() != null
                                    || (user.getCompanyId() == null && ApplicationInfo.PRODUCT_SUPPORT.equals(user.getUserType()))
                                    || (UserTypeUtil.isGovType(user.getUserType()))) {

                                if (event.getCode() == CommonBo.Account.LOGIN_ERROR_FIRSTLOGIN.getValue()) {
                                    Toast.makeText(this, "登陆成功，为了保证您的账户安全，请及时修改初始密码。", Toast.LENGTH_SHORT).show();
                                } else {
                                    Toast.makeText(this, getString(R.string.login_success), Toast.LENGTH_SHORT).show();
                                }

                                AppSharePreferenceUtil.getInstance().putString(SafeCloudConstants.CURRENT_USER, mGson.toJson(user));
                                Intent mIntent = new Intent(UserLoginActivity.this, MainNewActivity.class);
                                mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                startActivity(mIntent);
                            } else {
                                Toast.makeText(this, "公司为空，请联系管理员。", Toast.LENGTH_SHORT).show();
                            }

                        }

                    } else {
                        Toast.makeText(this, "登陆失败。", Toast.LENGTH_SHORT).show();
                    }
                    // ====== 用户身份判断 end ======
                } else {
                    mHUDUtil.showErrorTip(event.getMsg());
                }
            }
        }
    }

    @Override
    public void onLayoutChange(View v, int left, int top, int right,
                               int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {

        //现在认为只要控件将Activity向上推的高度超过了1/3屏幕高，就认为软键盘弹起
        if (popupWindow != null) {
            popupWindow.dismiss();
        }
        if (oldBottom != 0 && bottom != 0 && (oldBottom - bottom > keyHeight)) {
            isKeyBoardOn = true;
            //appIconImageView.setVisibility(View.GONE);
        } else if (oldBottom != 0 && bottom != 0 && (bottom - oldBottom > keyHeight)) {
            isKeyBoardOn = false;
            //appIconImageView.setVisibility(View.VISIBLE);
        }

    }

    private boolean checkPassword(String password) {
        return !(null == password || "".equals(password));
    }

    private boolean matcherPassword(String password) {

        //String pattern = "^[A-Za-z0-9]{6,25}$";
        String pattern = SafeCloudConstants.PASSWORD_CHECK;
        Pattern mPattern = Pattern.compile(pattern);
        Matcher mMatcher = mPattern.matcher(password);

        return mMatcher.matches();
    }

    private boolean checkAccountName(String account) {
        return !(null == account || "".equals(account));
    }


    private MaterialDialog materialDialog;

    private void showDialog() {
        materialDialog = new MaterialDialog.Builder(this)
                .content(R.string.please_wait)
                .progress(true, 0)
                .cancelable(false)
                .show();
    }

    private void cancelDialog() {
        if (materialDialog != null && materialDialog.isShowing()) {
            materialDialog.dismiss();
            materialDialog = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        cancelDialog();
    }

}
